package com.hotel.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hotel.dto.ReservationDTO;
import com.hotel.dto.ReservationPageQueryDTO;
import com.hotel.entity.Reservation;
import com.hotel.mapper.ReservationMapper;
import com.hotel.result.PageResult;
import com.hotel.service.ReservationService;
import com.hotel.vo.ReservationDetailVO;
import com.hotel.vo.ReservationVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements ReservationService {

    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 预约分页查询
     * @param reservationPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(ReservationPageQueryDTO reservationPageQueryDTO) {
        PageHelper.startPage(reservationPageQueryDTO.getPage(), reservationPageQueryDTO.getPageSize());
        Page<ReservationVO> page = reservationMapper.pageQuery(reservationPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据id查询预约信息
     * @param id
     * @return
     */
    @Override
    public ReservationDetailVO getDetailById(Integer id) {
        return reservationMapper.getDetailById(id);
    }

    @Override
    public void updateReservation(ReservationDTO reservationDTO) {
        //属性拷贝
        Reservation reservation = new Reservation();
        BeanUtils.copyProperties(reservationDTO, reservation);

        //计算预计金额
        //计算入住天数，日期相减为入住天数。若相减为0，则入住天数为1
        int checkInDay = reservationDTO.getCheckInDate().getDayOfMonth();
        int checkOutDay = reservationDTO.getCheckOutDate().getDayOfMonth();
        int duration = checkInDay - checkOutDay;
        if (duration == 0) {
            duration = 1;
        }
        //如果预计离开时间大于下午14：00，则天数加1
        if (reservationDTO.getCheckOutDate().getHour() >= 14) {
            duration++;
        }

        //预计金额=入住天数*房间单价
        BigDecimal expectedCost = BigDecimal.valueOf(100.00 * duration);
        reservation.setExpectedCost(expectedCost);
        //预付金额=预计金额*0.1
        BigDecimal advancePayment = expectedCost.multiply(new BigDecimal("0.1"));
        reservation.setAdvancePayment(advancePayment);

        reservationMapper.updateById(reservation);
    }

    @Override
    public void cancel(Integer id) {
        reservationMapper.cancel(id);
    }
}
